import { redux } from '@ohif/core';
import { connect } from 'react-redux';
import StudyBrowser from './StudyBrowser';

const { setActiveViewportSpecificData } = redux.actions;

// TODO
// - Determine in which display set is active from Redux (activeViewportIndex and layout viewportData)
// - Pass in errors and stack loading progress from Redux
const mapStateToProps = state => {
  let activeDisplaySetUID;
  const { viewportSpecificData, activeViewportIndex } = state.viewports[state.viewports.viewMode];
  if (viewportSpecificData[activeViewportIndex]) {
    activeDisplaySetUID = viewportSpecificData[activeViewportIndex].displaySetInstanceUID;
  }
  return {
    activeDisplaySetUID,
  };
};

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    onThumbnailClick: displaySetInstanceUID => {
      const findDisplaySetByUID = (studyMetadata, displaySetInstanceUID) => {
        if (!Array.isArray(studyMetadata)) return null;

        const allDisplaySets = studyMetadata.reduce((all, current) => {
          let currentDisplaySet = [];
          if (current && Array.isArray(current.displaySets)) {
            currentDisplaySet = current.displaySets;
          }
          return all.concat(currentDisplaySet);
        }, []);

        const bySetInstanceUID = ds =>
          ds.displaySetInstanceUID === displaySetInstanceUID;

        const displaySet = allDisplaySets.find(bySetInstanceUID);
        return displaySet || null;
      };

      let displaySet = findDisplaySetByUID(
        ownProps.studies,
        displaySetInstanceUID
      );

      if (displaySet.isDerived) {
        const { Modality } = displaySet;

        displaySet = displaySet.getSourceDisplaySet(ownProps.studyMetadata);

        if (!displaySet) {
          throw new Error(
            `Referenced series for ${Modality} dataset not present.`
          );
        }

        if (!displaySet) {
          throw new Error('Source data not present');
        }
      }

      dispatch(setActiveViewportSpecificData(displaySet));
    },
  };
};

const ConnectedStudyBrowser = connect(
  mapStateToProps,
  mapDispatchToProps
)(StudyBrowser);

export default ConnectedStudyBrowser;
